package com.dhgate.amazonCraw.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 管理redis的连接
 * @author lidongyang
 * @createtime Jan 16, 2013 10:29:35 AM
 */
public class RedisConnManager {
	/**
	 * 线程池对象
	 */
	private static JedisPool jedisPool = null;
	
	/**
	 * 初始化Jedis线程池
	 */
	static {
		RedisParam redisParam = RedisConifg.getRedisParam();//取得Jedis线程池的相关参数
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxActive(Integer.valueOf(redisParam.getMaxActive()));
		jedisPoolConfig.setMaxIdle(Integer.valueOf(redisParam.getMaxIdle()));
		jedisPoolConfig.setMaxWait(Integer.valueOf(redisParam.getMaxWait()));
		jedisPoolConfig.setTestOnBorrow(Boolean.valueOf(redisParam.getTestOnBorrow()));
		jedisPoolConfig.setTestOnReturn(Boolean.valueOf(redisParam.getTestOnReturn()));
		jedisPool = new JedisPool(jedisPoolConfig, redisParam.getServerIp(), Integer.valueOf(redisParam.getServerPort()), 10000);
	}
	
	/**
	 * 获取Jedis实例
	 * @return
	 */
	public static Jedis getJedis() {
		return jedisPool.getResource();
	}
	
	public static JedisPool getJedisPool() {
		return jedisPool;
	}
	
	/**
	 * 释放Jedis实例到线程池
	 * @param jedis
	 */
	public static void returnResource(Jedis jedis) {
		if(jedis != null) {
			jedisPool.returnResource(jedis);
		}
	}
	
}
